<template>
  <div class="container">
    <!-- 顶部搜索区域 -->
    <el-card class="search-card" shadow="never">
      <div class="search-wrapper">
        <el-form :inline="true" :model="queryParams" class="demo-form-inline">
          <el-form-item label="项目信息">
            <el-input
              :model-value="selectedProject ? selectedProject.name : ''"
              placeholder="请选择项目"
              readonly
              class="selector-input"
            >
              <template #append>
                <el-button @click="openProjectSelector" v-permission="['historicalQuotation:view']">选择</el-button>
              </template>
            </el-input>
          </el-form-item>
          <el-form-item>
            <el-input
              v-model="queryParams.code"
              placeholder="请输入编号"
              clearable
              style="width: 220px"
            />
          </el-form-item>
          <el-form-item>
            <el-button type="primary" :icon="Search" @click="handleQuery" v-permission="['historicalQuotation:view']">
              搜索
            </el-button>
            <el-button :icon="Refresh" @click="resetQuery" v-permission="['historicalQuotation:view']">
              重置
            </el-button>
            <el-button type="success" :icon="Plus" @click="handleCreate" v-permission="['historicalQuotation:edit']">
              新增报价单
            </el-button>
          </el-form-item>
        </el-form>
      </div>
    </el-card>

    <!-- 数据列表 -->
    <el-card class="list-card" shadow="never">
      <el-table
        v-loading="loading"
        :data="dataList"
        :height="tableHeight"
        element-loading-text="加载中..."
        element-loading-background="rgba(255, 255, 255, 0.7)"
        style="width: 100%"
        stripe
        border
      >
      
        <el-table-column type="index" width="60" label="序号" align="center" />
        <el-table-column prop="code" label="编号" min-width="120" align="center" show-overflow-tooltip />
        <el-table-column prop="projectName" label="项目名称" min-width="150" align="center" show-overflow-tooltip />
        <el-table-column prop="createTime" label="创建时间" min-width="180" align="center" show-overflow-tooltip>
          <template #default="scope">
            <span class="date-value">{{ formatDate(scope.row.createTime) }}</span>
          </template>
        </el-table-column>
        <el-table-column prop="createName" label="创建人" min-width="120" align="center" show-overflow-tooltip>
          <template #default="scope">
            <span>{{ scope.row.createName || '-' }}</span>
          </template>
        </el-table-column>
        <el-table-column prop="updateTime" label="更新时间" min-width="180" align="center" show-overflow-tooltip>
          <template #default="scope">
            <span class="date-value">{{ formatDate(scope.row.updateTime) }}</span>
          </template>
        </el-table-column>
        <el-table-column prop="updateName" label="更新人" min-width="120" align="center" show-overflow-tooltip>
          <template #default="scope">
            <span>{{ scope.row.updateName || '-' }}</span>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="200" align="center" fixed="right">
          <template #default="scope">
            <el-button type="primary" size="small" @click="handleViewDetail(scope.row.id)" v-permission="['historicalQuotation:view']">
              查看详情
            </el-button>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页区域 -->
      <div class="pagination">
        <el-pagination
          v-model:current-page="queryParams.page"
          v-model:page-size="queryParams.limit"
          :page-sizes="[10, 20, 50, 100]"
          :background="true"
          layout="prev, pager, next, jumper,->,sizes,total"
          :total="total"
          @current-change="handleCurrentChange"
          @size-change="handleSizeChange"
        />
      </div>
    </el-card>

    <!-- 项目选择器对话框 -->
    <ArchiveSelector
      v-model="projectSelectorVisible"
      title="选择项目"
      :search-fields="projectSearchFields"
      :table-columns="projectTableColumns"
      :fetch-data-api="getProjectList"
      :multiple="false"
      @confirm="handleProjectSelect"
    />
    
    <!-- 新增报价单对话框 -->
    <el-dialog
      v-model="createQuotationDialog.visible"
      title="新增报价单"
      width="500px"
      :close-on-click-modal="false"
      append-to-body
    >
      <el-form label-width="100px">
        <el-form-item label="选择项目">
          <el-select 
            v-model="createQuotationDialog.projectId" 
            placeholder="请选择项目" 
            style="width: 100%"
            filterable
          >
            <el-option
              v-for="item in projectOptions"
              :key="item.id"
              :label="item.name"
              :value="item.id"
            />
          </el-select>
        </el-form-item>
      </el-form>
      
      <template #footer>
        <el-button @click="createQuotationDialog.visible = false">取消</el-button>
        <el-button type="primary" @click="confirmCreateQuotation" :loading="createQuotationDialog.loading">
          确认
        </el-button>
      </template>
    </el-dialog>

    <!-- 报价单对话框 -->
    <el-dialog
      v-model="quotationDialog.visible"
      title="报价单详情"
      width="90%"
      :close-on-click-modal="false"
      :close-on-press-escape="false"
      v-loading="quotationDialog.loading"
      append-to-body
    >
      <div>
        <div class="quotation-actions">
          <el-button type="primary" :icon="Printer" @click="printQuotation">打印报价单</el-button>
          <el-button type="success" @click="saveQuotation">保存报价单</el-button>
          <el-button type="warning" :icon="Plus" @click="openMaterialSelect">新增物料</el-button>
        </div>
        
        <div class="quotation-container" id="quotationContent">
          <!-- LOGO - 置于最顶层右上角 -->
          <div class="top-logo">
            <img :src="logo" alt="公司logo" class="logo-image">
          </div>
          
          <!-- 基本信息表格 -->
          <table class="budget-table">
            <!-- 标题行 -->
            <tr>
              <td colspan="4" style="text-align: center; font-size: 18px; font-weight: bold; padding: 15px;">
                <el-input v-model="quotationData.title" />
              </td>
            </tr>
            
            <!-- 价格合计大写 -->
            <tr style="background-color: #ADD8E6;">
              <td colspan="2" style="text-align: center; font-weight: bold; padding: 8px;">价格合计大写：</td>
              <td colspan="2" style="text-align: center; padding: 8px;">{{ currentTotalAmountInChinese }}</td>
            </tr>
            
            <!-- 价格合计小写（千分位显示） -->
            <tr style="background-color: #ADD8E6;">
              <td colspan="2" style="text-align: center; font-weight: bold; padding: 8px;">价格合计小写：</td>
              <td colspan="2" style="text-align: center; padding: 8px;">{{ Number(currentTotalAmount).toLocaleString('zh-CN', { minimumFractionDigits: 2, maximumFractionDigits: 2 }) }}</td>
            </tr>
            
            <!-- 基本信息行 - 每行两个字段 -->
            <tr>
              <td style="background-color: #f0f0f0; text-align: left; font-weight: bold; width: 15%; padding: 8px;">报价单位：</td>
              <td style="width: 35%; padding: 8px;">
                <el-input v-model="quotationData.quotationUnit" placeholder="浙江中扬立库技术有限公司" />
              </td>
              <td style="background-color: #f0f0f0; text-align: left; font-weight: bold; width: 15%; padding: 8px;">报价人：</td>
              <td style="width: 35%; padding: 8px;">
                <el-input v-model="quotationData.person" placeholder="董春辉" />
              </td>
            </tr>
            
            <tr>
              <td style="background-color: #f0f0f0; text-align: left; font-weight: bold; padding: 8px;">询价单位：</td>
              <td style="padding: 8px;">
                <el-input v-model="quotationData.customerName" placeholder="请输入询价单位" />
              </td>
              <td style="background-color: #f0f0f0; text-align: left; font-weight: bold; padding: 8px;">收件人：</td>
              <td style="padding: 8px;">
                <el-input v-model="quotationData.customerContact" placeholder="请输入收件人" />
              </td>
            </tr>
            
            <tr>
              <td style="background-color: #f0f0f0; text-align: left; font-weight: bold; padding: 8px;">交货期：</td>
              <td style="padding: 8px;">
                <el-input v-model="quotationData.deliveryDate" placeholder="签订合同后款到账后立即配货，150天" />
              </td>
              <td style="background-color: #f0f0f0; text-align: left; font-weight: bold; padding: 8px;">报价日期：</td>
              <td style="padding: 8px;">
                <el-input v-model="quotationData.quotationDate" placeholder="2025/6/23" />
              </td>
            </tr>
            
            <tr>
              <td style="background-color: #f0f0f0; text-align: left; font-weight: bold; padding: 8px;">项目类型</td>
              <td style="padding: 8px;">
                <el-input v-model="quotationData.projectType" placeholder="国内项目" />
              </td>
              <td style="background-color: #f0f0f0; text-align: left; font-weight: bold; padding: 8px;">联系电话：</td>
              <td style="padding: 8px;">
                <el-input v-model="quotationData.customerPhone" placeholder="18702172783" />
              </td>
            </tr>
            
            <tr>
              <td style="background-color: #f0f0f0; text-align: left; font-weight: bold; padding: 8px;">联系邮箱</td>
              <td style="padding: 8px;">
                <el-input v-model="quotationData.email" placeholder="例如：XXXXX@XX.例如：XXXXX " />
              </td>
              <td style="background-color: #f0f0f0; text-align: left; font-weight: bold; padding: 8px;">报价有效期：</td>
              <td style="padding: 8px;">
                <el-input v-model="quotationData.validityPeriod" placeholder="15天" />
              </td>
            </tr>
            <tr>
              <td style="background-color: #f0f0f0; text-align: left; font-weight: bold; width: 15%; padding: 8px;">项目安装地址</td>
              <td  colspan="3" style="padding: 8px;">
                <el-input 
                  v-model="quotationData.installAddress" 
                  type="textarea"
                  :rows="2"
                  placeholder="例如：安徽省合肥市蜀山区"
                  style="width: 100%;"
                />
              </td>
            </tr>
            <tr>
              <td style="background-color: #f0f0f0; text-align: left; font-weight: bold; width: 15%; padding: 8px;">付款方式：</td>
              <td colspan="3" style="padding: 8px;">
                <el-input 
                  v-model="quotationData.paymentMethod" 
                  type="textarea"
                  :rows="2"
                  placeholder="预付35%定金，设备进场前支付30%，安装验收合格后1个月内支付30%，剩余5%质保1年。"
                  style="width: 100%;"
                />
              </td>
            </tr>
            
            <tr>
              <td style="background-color: #f0f0f0; text-align: left; font-weight: bold; width: 15%; padding: 8px;">特别说明：</td>
              <td colspan="3" style="padding: 8px;">
                <el-input 
                  v-model="quotationData.remarks" 
                  type="textarea"
                  :rows="2"
                  placeholder="本报价单为初步预算，按照贵方的图纸和所列设备清单。合同最终成交价按实际订制的设备清单为准（含税、含运费）"
                  style="width: 100%;"
                />
              </td>
            </tr>
          </table>
                    
          <!-- 报价明细表格 -->
          <table class="budget-table detail-table">
            <!-- 明细表头 -->
            <thead>
              <tr style="background-color: #FFFF00;">
                <td colspan="7" style="text-align: center; font-weight: bold; padding: 10px;">报价明细清单</td>
              </tr>
              
              <!-- 产品明细表头 -->

            </thead>
            
            <tbody>
            
            <!-- 按分类分组显示数据 -->
            <template v-for="(category, categoryIndex) in quotationData.categories" :key="category.id">
              <!-- 分类标题行 -->
              <tr class="category-row">
                <td colspan="7" class="category-name">
                  <el-input 
                    v-model="category.categoryName" 
                    placeholder="请输入分类名称"
                    style="width: 100%;"
                  />
                </td>
              </tr>
              
              <!-- 产品明细表头 -->
              <tr style="background-color: #f2f2f2;" class="table-header repeating-header">
                <td style="width: 18%; font-weight: bold; vertical-align: middle;">产品明细</td>
                <td style="width: 35%; font-weight: bold; vertical-align: middle;">设备型号及规格</td>
                <td style="width: 5%; font-weight: bold; vertical-align: middle;">数量</td>
                <td style="width: 5%; font-weight: bold; vertical-align: middle;">单位</td>
                <td style="width: 12%; font-weight: bold; vertical-align: middle;">品牌</td>
                <td style="width: 12%; font-weight: bold; vertical-align: middle;">单价（元）</td>
                <td style="width: 13%; font-weight: bold; vertical-align: middle;">总价（元）</td>
              </tr>
              
              <!-- 分类下的商品项 -->
              <template v-for="(item, itemIndex) in category.items" :key="item.id">
                <!-- 如果有规格表格数据，在规格列显示表格 -->
                <template v-if="item.specTable && item.specTable.length > 0">
                  <tr>
                    <td>
                      <el-input 
                        v-model="item.name" 
                        placeholder="请输入产品名称"
                        style="width: 100%;"
                      />
                    </td>
                    <td>
                      <!-- 规格信息动态显示 -->
                      <div class="spec-simple-layout">
                        <template v-for="(spec, specIndex) in item.specTable" :key="`spec-${itemIndex}-${specIndex}`">
                          <div class="spec-item">
                            <div class="spec-line">
                              <el-input 
                                v-model="spec.label" 
                                placeholder="规格信息"
                                size="small"
                                style="width: 100%; font-size: 11px; text-align: center;"
                              />
                            </div>
                          </div>
                        </template>
                      </div>
                    </td>
                    <td>
                      <el-input 
                        v-model="item.quantity" 
                        @input="updateItemTotalPrice(item)"
                        @blur="updateItemTotalPrice(item)"
                        placeholder="数量"
                        style="width: 100%; font-size: 12px;"
                        size="small"
                      />
                    </td>
                    <td>
                      <el-input 
                        v-model="item.unit" 
                        placeholder="单位"
                        style="width: 100%; font-size: 12px;"
                        size="small"
                      />
                    </td>
                    <td>
                      <el-input 
                        v-model="item.brand" 
                        placeholder="品牌"
                        style="width: 100%;"
                      />
                    </td>
                    <td>
                      <el-input 
                        v-model="item.unitPrice" 
                        @input="updateItemTotalPrice(item)"
                        @blur="formatUnitPrice(item); updateItemTotalPrice(item)"
                        placeholder="单价"
                        style="width: 100%;"
                      />
                    </td>
                    <td>
                      <el-input 
                        v-model="item.totalPrice" 
                        placeholder="总价"
                        readonly
                        style="width: 100%; background-color: #f5f7fa;"
                      />
                    </td>
                  </tr>
                </template>
                
                <!-- 如果没有规格表格数据，按原格式显示 -->
                <template v-else>
                  <tr>
                    <td>
                      <el-input 
                        v-model="item.name" 
                        placeholder="请输入产品名称"
                        style="width: 100%;"
                      />
                    </td>
                    <td colspan="1" style="vertical-align: top; word-wrap: break-word; overflow-wrap: break-word;">
                      <el-input 
                        v-model="item.spec" 
                        type="textarea"
                        :rows="2"
                        placeholder="请输入规格说明"
                        style="width: 100%; text-align: left; word-wrap: break-word;"
                      />
                    </td>
                    <td>
                      <el-input 
                        v-model="item.quantity" 
                        @input="updateItemTotalPrice(item)"
                        @blur="updateItemTotalPrice(item)"
                        placeholder="数量"
                        style="width: 100%; font-size: 12px;"
                        size="small"
                      />
                    </td>
                    <td>
                      <el-input 
                        v-model="item.unit" 
                        placeholder="单位"
                        style="width: 100%; font-size: 12px;"
                        size="small"
                      />
                    </td>
                    <td>
                      <el-input 
                        v-model="item.brand" 
                        placeholder="品牌"
                        style="width: 100%;"
                      />
                    </td>
                    <td>
                      <el-input 
                        v-model="item.unitPrice" 
                        @input="updateItemTotalPrice(item)"
                        @blur="formatUnitPrice(item); updateItemTotalPrice(item)"
                        placeholder="单价"
                        style="width: 100%;"
                      />
                    </td>
                    <td>
                      <el-input 
                        v-model="item.totalPrice" 
                        placeholder="总价"
                        readonly
                        style="width: 100%; background-color: #f5f7fa;"
                      />
                    </td>
                  </tr>
                </template>
              </template>
              
              <!-- 分类汇总价格行 -->
              <tr style="background-color: #e6f7ff; font-weight: bold;" class="category-total">
                <td colspan="6" style="text-align: right; padding: 8px;">{{ category.categoryName }} 小计：</td>
                <td style="text-align: center; padding: 8px;">{{ formatPrice(getCategoryTotal(category)) }}</td>
              </tr>
              
              <!-- 分类操作行 -->
              <tr class="no-print">
                <td colspan="7" style="text-align: right; padding: 5px;">
                  <el-button type="primary" size="small" @click="addItemToCategory(category)">
                    <el-icon><Plus /></el-icon>
                    添加项目
                  </el-button>
                  <el-button type="warning" size="small" @click="removeLastItemFromCategory(category)">
                    <el-icon><Delete /></el-icon>
                    删除最后一个项目
                  </el-button>
                  <el-button type="danger" size="small" @click="removeCategory(categoryIndex)">
                    <el-icon><Delete /></el-icon>
                    删除分类
                  </el-button>
                </td>
              </tr>
            </template>
            
            <!-- 添加分类按钮行 -->
            <tr class="no-print">
              <td colspan="7" style="text-align: center; padding: 10px;">
                <el-button type="success" @click="addNewCategory">
                  <el-icon><Plus /></el-icon>
                  添加新分类
                </el-button>
              </td>
            </tr>
            
            <!-- 备注行 -->
            <tr style="background-color: #f8f9fa;">
              <td style="background-color: #e9ecef; text-align: center; font-weight: bold; vertical-align: middle; padding: 12px; border-right: 2px solid #dee2e6; color: #495057; font-size: 14px;">
                <i class="el-icon-document" style="margin-right: 5px;"></i>备注说明
              </td>
              <td colspan="6" style="padding: 12px; background-color: #ffffff; border: 1px solid #dee2e6;">
                <el-input 
                  v-model="quotationData.additionalRemarks" 
                  type="textarea"
                  :rows="4"
                  placeholder="1. 以上报价根据国家税率涨幅含增值税发票；&#10;2. 报价有效期：30天&#10;3. 付款方式：预付40%，发货付30%，验收合格付30%&#10;4. 其他说明事项..."
                  style="width: 100%; border-radius: 4px;"
                  class="remarks-textarea"
                />
              </td>
            </tr>
            
            </tbody>
          </table>
        </div>
      </div>
    </el-dialog>
    
    <!-- 物料选择对话框 -->
    <material-dialog
      ref="materialDialogRef"
      :multiple="true"
      @handleMaterialSelectionChange="handleMaterialSelectionChange"
      @confirmMaterialSelect="confirmMaterialSelect"
    />
  </div>
</template>

<script lang="ts" setup>
import { ref, reactive, onMounted, nextTick, computed } from 'vue'
import { useRouter } from 'vue-router'
import { getHistoricalQuotationListApi, saveStructureQuotationApi, getQuotationDataByProjectIdApi,getQuotationDataFromPricingModulesApi } from '@/api/historicalQuotation/index'
import type { HistoricalQuotation, HistoricalQuotationQuery, QuotationSheet } from '@/api/historicalQuotation/type'
import { Search, Refresh, Plus, Printer, Delete } from '@element-plus/icons-vue'
import ArchiveSelector from "@/components/common/ArchiveSelector.vue"
import { getSimpleProject, getProjectDocumentApi } from '@/api/project'
import { ElMessage, ElMessageBox } from 'element-plus'
import {getProjectDocumentListApi} from "@/api/project";
import { ProjectDocument, ProjectDocumentListParam } from '@/api/project/type'

// 导入logo图片
import logo from '@/assets/logo.png'
// 导入物料选择对话框组件
import MaterialDialog from '@/views/baseInfo/material/materialDialog/index.vue'
// 引入统一格式化工具
import { formatPrice } from '@/utils/formatter'

// 遮罩层
const loading = ref(true)
// 总条数
const total = ref(0)
// 历史报价单表格数据
const dataList = ref<HistoricalQuotation[]>([])
// 表格高度自适应
const tableHeight = ref(0)

// 项目选项
const projectOptions = ref<any[]>([])

// 选中的项目
const selectedProject = ref<ProjectDocument | null>(null)

// 查询参数
const queryParams = reactive<HistoricalQuotationQuery>({
  page: 1,
  limit: 10,
  projectId: undefined,
  code: undefined
})

// 项目选择器相关
const projectSelectorVisible = ref(false)
const projectSearchFields = [
  { label: '项目编号', prop: 'code', type: 'input' as const },
  { label: '项目名称', prop: 'name', type: 'input' as const }
]
const projectTableColumns = [
  { label: '项目编号', prop: 'code' },
  { label: '项目名称', prop: 'name' },
  { label: '项目状态', prop: 'status' }
]

// 新增报价单对话框
const createQuotationDialog = reactive({
  visible: false,
  projectId: null as number | null,
  loading: false
})

// 报价单对话框
const quotationDialog = reactive({
  visible: false,
  projectId: null as number | null,
  projectName: '',
  loading: false
})

// 报价单数据 - 基于后端返回的数据结构
const quotationData = reactive<QuotationSheet & {
  deliveryDate?: string
  projectType?: string
  installAddress?: string
  email?: string
  validityPeriod?: string
  additionalRemarks?: string
}>({
  id: '',
  customerName: '',
  customerContact: '董春辉',
  customerPhone: '18702172783',
  quotationDate: new Date().toISOString().split('T')[0],
  validDays: 30,
  paymentMethod: '预付40%，发货付30%，验收合格付30%(现汇)',
  totalAmount: 0,
  remarks: '',
  title: '',
  categories: [],
            // 额外字段
  deliveryDate: '合同签订后30个工作日',
  projectType: '智能仓储物流系统集成',
  installAddress: '',
  email: '',
  validityPeriod: '报价单盖章后7天',
  additionalRemarks: '1. 以上报价根据国家税率涨幅含增值税发票；\n2. 报价有效期：30天\n3. 付款方式：预付40%，发货付30%，验收合格付30%'
})

// 物料选择相关
const materialDialogRef = ref()
const selectedMaterials = ref<any[]>([])

// 路由实例
const router = useRouter()

// 打开项目选择器
const openProjectSelector = () => {
  projectSelectorVisible.value = true
}


const getProjectList = async (params: any) => {
  try {
    // 构建查询参数
    const queryParams: ProjectDocumentListParam = {
      name: params.name,
      code: params.code,
      customer: params.customer,
      status: params.status,
      page: params.page || 1,
      limit: params.limit || 10
    };

    // 调用项目列表API - 使用真实API
    return await getProjectDocumentListApi(queryParams);
  } catch (error) {
    console.error('获取项目列表失败:', error);
    return {data: {list: [], total: 0}};
  }
};
// 处理项目选择
// 处理项目选择确认
const handleProjectSelect = (project: ProjectDocument) => {
  selectedProject.value = project;
  console.log('选择的项目:', project);
  queryParams.projectId = project.id || 0;
};
// 获取项目选项
const getProjectOptions = async () => {
  try {
    const res = await getSimpleProject()
    projectOptions.value = res.data || []
  } catch (error) {
    console.error('获取项目列表失败', error)
  }
}

// 查询历史报价单列表
const getList = async () => {
  loading.value = true
  try {
    const res = await getHistoricalQuotationListApi(queryParams)
    dataList.value = res.data.list
    total.value = res.data.total
  } catch (error) {
    console.error('获取历史报价单列表失败', error)
  } finally {
    loading.value = false
  }
}

// 搜索按钮操作
const handleQuery = () => {
  queryParams.page = 1
  getList()
}

// 重置按钮操作
const resetQuery = () => {
  selectedProject.value = null
  queryParams.projectId = undefined
  queryParams.code = undefined
  queryParams.page = 1
  getList()
}

// 查看详情按钮操作
const handleViewDetail = (id: number) => {
  router.push({ path: `/compute/historicalQuotation/detail/${id}` })
}

// 每页数量改变
const handleSizeChange = (size: number) => {
  queryParams.limit = size
  getList()
}

// 页码改变
const handleCurrentChange = (page: number) => {
  queryParams.page = page
  getList()
}

// 格式化日期
const formatDate = (date: string) => {
  if (!date) return ''
  return new Date(date).toLocaleString()
}

// 格式化货币
const formatCurrency = (amount: number) => {
  if (amount === 0) return '0.00'
  return new Intl.NumberFormat('zh-CN', {
    minimumFractionDigits: 2,
    maximumFractionDigits: 2
  }).format(amount)
}

// 格式化金额为大写
const convertToChinese = (money: number) => {
  if (money === 0) {
    return '零元整'
  }
  
  const fraction = ['角', '分']
  const digit = ['零', '壹', '贰', '叁', '肆', '伍', '陆', '柒', '捌', '玖']
  const unit = [
    ['元', '万', '亿'],
    ['', '拾', '佰', '仟']
  ]
  const head = money < 0 ? '负' : ''
  
  money = Math.abs(money)
  
  let s = ''
  
  for (let i = 0; i < fraction.length; i++) {
    s += (digit[Math.floor(money * 10 * Math.pow(10, i)) % 10] + fraction[i]).replace(/零./, '')
  }
  
  s = s || '整'
  
  money = Math.floor(money)
  
  for (let i = 0; i < unit[0].length && money > 0; i++) {
    let p = ''
    for (let j = 0; j < unit[1].length && money > 0; j++) {
      p = digit[money % 10] + unit[1][j] + p
      money = Math.floor(money / 10)
    }
    s = p.replace(/(零.)*零$/, '').replace(/^$/, '零') + unit[0][i] + s
  }
  
  return head + s.replace(/(零.)*零元/, '元').replace(/(零.)+/g, '零').replace(/^整$/, '零元整')
}

// 格式化单价为两位小数
const formatUnitPrice = (item: any) => {
  if (item.unitPrice !== '' && item.unitPrice !== null && item.unitPrice !== undefined) {
    const price = Number(item.unitPrice) || 0
    item.unitPrice = price.toFixed(2)
  }
}

// 更新项目总价
const updateItemTotalPrice = (item: any) => {
  const quantity = Number(item.quantity) || 0
  const unitPrice = Number(item.unitPrice) || 0
  
  // 无论数值是否大于0都进行计算，包括0值情况
  item.totalPrice = Number((quantity * unitPrice).toFixed(2))
  
  // 立即重新计算总金额
  calculateTotalAmount()
}

// 计算总价
const calculateTotalAmount = () => {
  let total = 0
  if (quotationData.categories) {
    quotationData.categories.forEach(category => {
      if (category.items) {
        category.items.forEach(item => {
          // 确保数值类型正确
          const quantity = Number(item.quantity) || 0
          const unitPrice = Number(item.unitPrice) || 0
          
          // 自动计算每项的总价
          item.totalPrice = Number((quantity * unitPrice).toFixed(2))
          
          // 累加到总金额
          total += Number(item.totalPrice) || 0
        })
      }
    })
  }
  quotationData.totalAmount = Number(total.toFixed(2))
  return quotationData.totalAmount
}

// 计算总额大写
const totalAmountInChinese = () => {
  // 先计算最新的总金额
  calculateTotalAmount()
  return convertToChinese(quotationData.totalAmount || 0)
}

// 计算属性：实时更新的总金额
const currentTotalAmount = computed(() => {
  let total = 0
  if (quotationData.categories) {
    quotationData.categories.forEach(category => {
      if (category.items) {
        category.items.forEach(item => {
          const quantity = Number(item.quantity) || 0
          const unitPrice = Number(item.unitPrice) || 0
          total += quantity * unitPrice
        })
      }
    })
  }
  return Number(total.toFixed(2))
})

// 计算属性：实时更新的总金额大写
const currentTotalAmountInChinese = computed(() => {
  return convertToChinese(currentTotalAmount.value)
})


// 计算单个分类的总价
const getCategoryTotal = (category: any) => {
  if (!category.items || category.items.length === 0) {
    return 0
  }
  
  let total = 0
  category.items.forEach((item: any) => {
    const quantity = Number(item.quantity) || 0
    const unitPrice = Number(item.unitPrice) || 0
    total += quantity * unitPrice
  })
  
  return Number(total.toFixed(2))
}

// 获取规格数据生成简单布局HTML的辅助函数
const generateSpecHtml = (specTable: any[]) => {
  let html = '<div style="padding: 8px; font-size: 11px; line-height: 1.4;">'
  
  // 动态显示所有规格行
  if (specTable && specTable.length > 0) {
    specTable.forEach((spec, index) => {
      if (spec && spec.label) {
        html += '<div style="margin-bottom: 3px; padding-bottom: 3px;'
        // 除了最后一行，其他行都加分割线
        if (index < specTable.length - 1) {
          html += ' border-bottom: 1px solid #e8e8e8;'
        }
        html += '">'
        html += '<span style="color: #333; text-align: center !important; display: block; width: 100%;">' + (spec.label || '') + '</span>'
        html += '</div>'
      }
    })
  } else {
    // 没有数据时显示占位符
    html += '<div style="text-align: center; color: #ccc;">暂无规格信息</div>'
  }
  
  html += '</div>'
  return html
}

// 新增报价单方法
const handleCreate = () => {
  createQuotationDialog.visible = true
  createQuotationDialog.projectId = null
}

// 确认创建报价单
const confirmCreateQuotation = async () => {
  if (!createQuotationDialog.projectId) {
    ElMessage.warning('请先选择项目')
    return
  }
  
  try {
    createQuotationDialog.loading = true
    
    // 根据项目获取报价单数据
    const res = await getQuotationDataFromPricingModulesApi(createQuotationDialog.projectId)
    if (res.code === 200 && res.data) {
      // 设置报价单项目信息
      quotationDialog.projectId = createQuotationDialog.projectId
      quotationDialog.projectName = projectOptions.value.find(p => p.id === createQuotationDialog.projectId)?.name || ''
      
      // 使用后端返回的完整数据结构
      Object.assign(quotationData, {
        id: res.data.id,
        title: res.data.title || '',
        customerName: res.data.customerName || '',
        customerContact: res.data.customerContact || '董春辉',
        customerPhone: res.data.customerPhone || '18702172783',
        quotationDate: res.data.quotationDate ? new Date(res.data.quotationDate).toISOString().split('T')[0] : new Date().toISOString().split('T')[0],
        validDays: res.data.validDays || 30,
        paymentMethod: res.data.paymentMethod || '预付40%，发货付30%，验收合格付30%',
        totalAmount: res.data.totalAmount || 0,
        remarks: res.data.remarks || '',
        person:res.data.person,
        quotationUnit:res.data.quotationUnit,
        installAddress:res.data.installAddress,
        email:res.data.email,
        categories: res.data.categories || []
      })
      
      // 关闭创建对话框，打开报价单对话框
      createQuotationDialog.visible = false
      quotationDialog.visible = true
      
      // 初始化时计算一次总价并格式化单价，确保数据同步
      nextTick(() => {
        // 格式化所有项目的单价
        if (quotationData.categories) {
          quotationData.categories.forEach(category => {
            if (category.items) {
              category.items.forEach(item => {
                formatUnitPrice(item)
              })
            }
          })
        }
        calculateTotalAmount()
      })
    } else {
      ElMessage.error(res.msg || '获取项目数据失败')
    }
  } catch (error) {
    console.error('创建报价单失败', error)
    ElMessage.error('创建报价单失败')
  } finally {
    createQuotationDialog.loading = false
  }
}

// 新的简洁打印报价单功能
const printQuotation = () => {
  try {
    // 生成打印用的HTML内容
    const printHtml = generatePrintHtml()
    
    // 创建打印窗口
    const printWindow = window.open('', '_blank', 'width=800,height=600')
    if (!printWindow) {
      ElMessage.error('无法打开打印窗口，请检查浏览器设置')
      return
    }
    
    // 写入HTML内容
    printWindow.document.write(printHtml)
    printWindow.document.close()
    
    // 自动打印
    printWindow.focus()
    setTimeout(() => {
      printWindow.print()
    }, 500)
    
  } catch (error) {
    console.error('打印失败', error)
    ElMessage.error('打印失败：' + ((error as Error).message || '未知错误'))
  }
}

// 生成打印用的HTML内容
const generatePrintHtml = () => {
  // 基础样式
  const styles = `
    <style>
      * { 
        margin: 0; 
        padding: 0; 
        box-sizing: border-box; 
      }
      
      body { 
        font-family: SimSun, serif; 
        font-size: 12px; 
        line-height: 1.4; 
        color: #333; 
        padding: 20px;
      }
      
      .quotation-container { 
        position: relative; 
        background: white; 
      }
      
      .top-logo { 
        position: absolute; 
        top: 10px; 
        right: 10px; 
        z-index: 1000; 
      }
      
      .logo-image { 
        max-width: 120px; 
        height: auto; 
      }
      
      .budget-table { 
        width: 100%; 
        border-collapse: collapse; 
        margin: 16px 0; 
      }
      
      .budget-table td { 
        padding: 8px; 
        border: 1px solid #333; 
        text-align: center !important; 
        vertical-align: middle; 
        font-size: 11px; 
        word-wrap: break-word; 
      }
      
      .category-row { 
        background-color: #3498db !important; 
      }
      
      .category-row td { 
        background-color: #3498db !important; 
        color: white !important; 
        font-weight: bold !important; 
      }
      
      .table-header { 
        background-color: #f2f2f2 !important; 
      }
      
      .table-header td { 
        background-color: #f2f2f2 !important; 
        font-weight: bold !important; 
        text-align: center !important;
        vertical-align: middle !important;
        padding: 8px !important;
      }
      
      .repeating-header {
        page-break-inside: avoid !important;
      }
      
      .category-total { 
        background-color: #ecf0f1 !important; 
        font-weight: bold !important; 
      }
      
      .spec-content { 
        text-align: center !important; 
        padding: 4px; 
        font-size: 10px; 
        line-height: 1.3; 
      }
      
      .spec-line { 
        margin-bottom: 3px;
        padding-bottom: 3px;
        text-align: center;
        border-bottom: 1px solid #e8e8e8;
      }
      
      .spec-line:last-child { 
        border-bottom: none; 
      }
      
      @media print {
        @page { 
          size: A4; 
          margin: 0.5in; 
        }
        
        body { 
          -webkit-print-color-adjust: exact; 
          print-color-adjust: exact; 
        }
        
        .budget-table td { 
          font-size: 9px !important; 
          padding: 6px 4px !important; 
          text-align: center !important;
        }
        
        .spec-content { 
          font-size: 8px !important; 
          text-align: center !important;
        }
        
        .spec-line { 
          text-align: center !important;
          border-bottom: 1px solid #e8e8e8 !important;
          padding-bottom: 2px !important;
          margin-bottom: 2px !important;
        }
        
        .spec-line:last-child { 
          border-bottom: none !important; 
        }
      }
    </style>
  `
  
  // 生成基本信息表格
  const basicInfoTable = `
    <table class="budget-table">
      <tr>
        <td colspan="4" style="font-size: 18px;height:60px; font-weight: bold; padding: 15px; text-align: center;">
          ${quotationData.title || ''}
        </td>
      </tr>
      <tr style="background-color: #ADD8E6;">
        <td colspan="2" style="font-weight: bold; text-align: center;">价格合计大写：</td>
        <td colspan="2" style="text-align: center;">${currentTotalAmountInChinese.value}</td>
      </tr>
      <tr style="background-color: #ADD8E6;">
        <td colspan="2" style="font-weight: bold; text-align: center;">价格合计小写：</td>
        <td colspan="2" style="text-align: center;">${formatPrice(currentTotalAmount.value)}</td>
      </tr>
      <tr>
        <td style="background-color: #f0f0f0; font-weight: bold; text-align: center;">报价单位：</td>
        <td style="text-align: center;">${quotationData.quotationUnit || '浙江中扬立库技术有限公司'}</td>
        <td style="background-color: #f0f0f0; font-weight: bold; text-align: center;">报价人：</td>
        <td style="text-align: center;">${quotationData.person || '董春辉'}</td>
      </tr>
      <tr>
        <td style="background-color: #f0f0f0; font-weight: bold; text-align: center;">询价单位：</td>
        <td style="text-align: center;">${quotationData.customerName || ''}</td>
        <td style="background-color: #f0f0f0; font-weight: bold; text-align: center;">收件人：</td>
        <td style="text-align: center;">${quotationData.customerContact || ''}</td>
      </tr>
      <tr>
        <td style="background-color: #f0f0f0; font-weight: bold; text-align: center;">交货期：</td>
        <td style="text-align: center;">${quotationData.deliveryDate || '签订合同后款到账后立即配货，150天'}</td>
        <td style="background-color: #f0f0f0; font-weight: bold; text-align: center;">报价日期：</td>
        <td style="text-align: center;">${quotationData.quotationDate || '2025/6/23'}</td>
      </tr>
      <tr>
        <td style="background-color: #f0f0f0; font-weight: bold; text-align: center;">项目类型：</td>
        <td style="text-align: center;">${quotationData.projectType || '国内项目'}</td>
        <td style="background-color: #f0f0f0; font-weight: bold; text-align: center;">联系电话：</td>
        <td style="text-align: center;">${quotationData.customerPhone || '18702172783'}</td>
      </tr>
      <tr>
        <td style="background-color: #f0f0f0; font-weight: bold; text-align: center;">联系邮箱：</td>
        <td style="text-align: center;">${quotationData.email || ''}</td>
        <td style="background-color: #f0f0f0; font-weight: bold; text-align: center;">报价有效期：</td>
        <td style="text-align: center;">${quotationData.validityPeriod || '15天'}</td>
      </tr>
      <tr>
        <td style="background-color: #f0f0f0; font-weight: bold; text-align: center;">项目安装地址：</td>
        <td colspan="3" style="text-align: center;">${quotationData.installAddress || ''}</td>
      </tr>
      <tr>
        <td style="background-color: #f0f0f0; font-weight: bold; text-align: center;">付款方式：</td>
        <td colspan="3" style="text-align: center;">${quotationData.paymentMethod || '预付35%定金，设备进场前支付30%，安装验收合格后1个月内支付30%，剩余5%质保1年。(现汇)'}</td>
      </tr>
      <tr>
        <td style="background-color: #f0f0f0; font-weight: bold; text-align: center;">特别说明：</td>
        <td colspan="3" style="text-align: center;">${quotationData.remarks || '本报价单为初步预算，按照贵方的图纸和所列设备清单。合同最终成交价按实际订制的设备清单为准（含税、含运费）'}</td>
      </tr>
    </table>
  `
  
  // 生成明细表格
  const detailTable = generateDetailTable()
  
  // 组合完整HTML
  const html = `
    <!DOCTYPE html>
    <html>
    <head>
      <meta charset="utf-8">
      <title>报价清单</title>
      ${styles}
    </head>
    <body>
      <div class="quotation-container">
        <div class="top-logo">
          <img src="${logo}" alt="公司logo" class="logo-image">
        </div>
        ${basicInfoTable}
        ${detailTable}
      </div>
    </body>
    </html>
  `
  
  return html
}

// 生成明细表格
const generateDetailTable = () => {
  let html = `
    <table class="budget-table">
      <thead>
        <tr style="background-color: #FFFF00;">
          <td colspan="7" style="font-weight: bold; padding: 10px; text-align: center;">报价明细清单</td>
        </tr>

      </thead>
      <tbody>
  `
  
        // 遍历分类
      if (quotationData.categories) {
        quotationData.categories.forEach(category => {
          // 分类标题行
          html += `
            <tr class="category-row">
              <td colspan="7" style="text-align: center; font-weight: bold; padding: 10px;">
                ${category.categoryName || ''}
              </td>
            </tr>
          `
          
          // 产品明细表头
          html += `
            <tr style="background-color: #f2f2f2;" class="table-header">
              <td style="width: 18%; font-weight: bold; vertical-align: middle; text-align: center; padding: 8px;">产品明细</td>
              <td style="width: 35%; font-weight: bold; vertical-align: middle; text-align: center; padding: 8px;">设备型号及规格</td>
              <td style="width: 5%; font-weight: bold; vertical-align: middle; text-align: center; padding: 8px;">数量</td>
              <td style="width: 5%; font-weight: bold; vertical-align: middle; text-align: center; padding: 8px;">单位</td>
              <td style="width: 12%; font-weight: bold; vertical-align: middle; text-align: center; padding: 8px;">品牌</td>
              <td style="width: 12%; font-weight: bold; vertical-align: middle; text-align: center; padding: 8px;">单价（元）</td>
              <td style="width: 13%; font-weight: bold; vertical-align: middle; text-align: center; padding: 8px;">总价（元）</td>
            </tr>
          `
          
          // 分类下的项目
      if (category.items) {
        category.items.forEach(item => {
          // 生成规格内容
          let specContent = ''
          if (item.specTable && item.specTable.length > 0) {
            const specs: string[] = []
            item.specTable.forEach((spec: any, index: number) => {
              if (spec && spec.label) {
                let divStyle = 'margin-bottom: 3px; padding-bottom: 3px; text-align: center;'
                // 除了最后一行，其他行都加分割线
                if (item.specTable && index < item.specTable.length - 1) {
                  divStyle += ' border-bottom: 1px solid #e8e8e8;'
                }
                specs.push(`<div class="spec-line" style="${divStyle}">${spec.label}</div>`)
              }
            })
            specContent = `<div class="spec-content">${specs.join('')}</div>`
          } else {
            specContent = item.spec || ''
          }
          
          html += `
            <tr>
              <td style="text-align: center;">${item.name || ''}</td>
              <td style="text-align: center;">${specContent}</td>
              <td style="text-align: center;">${item.quantity || ''}</td>
              <td style="text-align: center;">${item.unit || ''}</td>
              <td style="text-align: center;">${item.brand || ''}</td>
              <td style="text-align: center;">${formatPrice(Number(item.unitPrice) || 0)}</td>
              <td style="text-align: center;">${formatPrice(Number(item.totalPrice) || 0)}</td>
            </tr>
          `
        })
      }
      
      // 分类小计
      html += `
        <tr class="category-total">
          <td colspan="6" style="text-align: center; font-weight: bold;">${category.categoryName} 小计：</td>
          <td style="font-weight: bold; text-align: center;">${formatPrice(getCategoryTotal(category))}</td>
        </tr>
      `
    })
  }
  
  // 备注行
  html += `
      <tr style="background-color: #f8f9fa;">
        <td style="background-color: #e9ecef; font-weight: bold; text-align: center;">备注说明</td>
        <td colspan="6" style="text-align: center; padding: 12px;">
          ${quotationData.additionalRemarks || '1. 以上报价根据国家税率涨幅含增值税发票；\\n2. 报价有效期：30天\\n3. 付款方式：预付40%，发货付30%，验收合格付30%'}
        </td>
      </tr>
    </tbody>
    </table>
  `
  
  return html
}

// 保存报价单
const saveQuotation = async () => {
  if (!quotationDialog.projectId) {
    ElMessage.warning('请先选择项目')
    return
  }
  
  try {
    quotationDialog.loading = true
    
    // 使用新的HTML生成方式
    const printHtml = generatePrintHtml()
    
    // 构建保存参数
    const params = {
      projectId: quotationDialog.projectId,
      content: printHtml
    }
    
    // 调用保存接口
    const res = await saveStructureQuotationApi(params)
    
    if (res.code === 200) {
      ElMessage.success('保存成功')
      quotationDialog.visible = false
      getList() // 刷新列表
    } else {
      ElMessage.error(res.msg || '保存失败')
    }
  } catch (error) {
    console.error('保存报价单失败', error)
    ElMessage.error('保存报价单失败')
  } finally {
    quotationDialog.loading = false
  }
}

// 打开物料选择弹框
const openMaterialSelect = () => {
  if (!quotationDialog.visible) {
    ElMessage.warning('请先打开报价单详情')
    return
  }
  materialDialogRef.value.onShow(selectedMaterials.value)
}

// 处理物料选择变化
const handleMaterialSelectionChange = (selection: any) => {
  // 更新已选中的物料
  selectedMaterials.value = selection
}

// 确认物料选择
const confirmMaterialSelect = () => {
  if (selectedMaterials.value.length === 0) {
    ElMessage.warning('请至少选择一个物料')
    return
  }
  
  // 确保categories数组存在
  if (!quotationData.categories) {
    quotationData.categories = []
  }
  
  // 将选中的物料添加到报价单中
  selectedMaterials.value.forEach((material: any) => {
    const categoryName = material.categoryName || '未分类'
    
    // 查找或创建分类
    let category = quotationData.categories!.find(cat => cat.categoryName === categoryName)
    if (!category) {
      category = {
        id: `category_${Date.now()}_${Math.random()}`,
        categoryName: categoryName,
        items: []
      }
      quotationData.categories!.push(category)
    }
    
    // 确保items数组存在
    if (!category.items) {
      category.items = []
    }
    
    // 检查物料是否已存在
    const existingItem = category.items.find(item => 
      item.name === material.materialName && 
      item.spec === material.specification
    )
    
    if (!existingItem) {
      // 添加新物料项
      const newItem = {
        id: `item_${Date.now()}_${Math.random()}`,
        name: material.materialName || '',
        spec: material.specification || '',
        brand: material.brand || '',
        unit: material.unitName || '个',
        quantity: 1,
        unitPrice: (material.price || 0).toFixed(2),
        totalPrice: material.price || 0,
        optional: false
      }
      category.items.push(newItem)
    }
  })
  
  // 重新计算总金额
  calculateTotalAmount()
  
  ElMessage.success(`已添加 ${selectedMaterials.value.length} 个物料到报价单`)
  materialDialogRef.value.onClose()
  
  // 清空已选物料，为下次选择做准备
  selectedMaterials.value = []
}

// 添加项目到分类
const addItemToCategory = (category: any) => {
  if (!category.items) {
    category.items = []
  }
  
  const newItem = {
    id: `item_${Date.now()}_${Math.random()}`,
    name: '',
    spec: '',
    brand: 'Zoneyung',
    unit: '个',
    quantity: 1,
    unitPrice: '0.00',
    totalPrice: 0,
    optional: false
  }
  
  category.items.push(newItem)
}

// 删除分类中最后一个项目
const removeLastItemFromCategory = (category: any) => {
  if (!category.items || category.items.length === 0) {
    ElMessage.warning('该分类下没有项目可删除')
    return
  }
  
  ElMessageBox.confirm('确定要删除最后一个项目吗？', '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(() => {
    category.items.pop() // 删除最后一个项目
    // 重新计算总价
    nextTick(() => {
      calculateTotalAmount()
    })
    ElMessage.success('删除成功')
  }).catch(() => {
    // 用户取消删除
  })
}

// 删除分类
const removeCategory = (categoryIndex: number) => {
  ElMessageBox.confirm('确定要删除这个分类吗？', '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(() => {
    if (quotationData.categories) {
      quotationData.categories.splice(categoryIndex, 1)
      // 重新计算总价
      nextTick(() => {
        calculateTotalAmount()
      })
      ElMessage.success('删除成功')
    }
  }).catch(() => {
    // 用户取消删除
  })
}

// 添加新分类
const addNewCategory = () => {
  if (!quotationData.categories) {
    quotationData.categories = []
  }
  
  const newCategory = {
    id: `category_${Date.now()}_${Math.random()}`,
    categoryName: '新分类',
    items: []
  }
  
  quotationData.categories.push(newCategory)
}

onMounted(() => {
  getProjectOptions()
  getList()
  
  // 设置表格高度
  nextTick(() => {
    tableHeight.value = window.innerHeight - 260
  })
  
  // 监听窗口大小变化
  window.addEventListener('resize', () => {
    nextTick(() => {
      tableHeight.value = window.innerHeight - 260
    })
  })
})
</script>

<style scoped lang="scss">
.container {
  padding: 20px 20px 0px;

  /*顶部搜索卡片*/
  .search-card {
    margin-bottom: 20px;

    :deep(.el-card__body) {
      padding: 15px 20px;
    }

    /*搜索表单*/
    .search-wrapper {
      .demo-form-inline {
        .el-form-item {
          margin-bottom: 0;
          margin-right: 15px;

          &:last-child {
            margin-right: 0;
          }

          .separator {
            margin: 0 5px;
            color: #909399;
          }
        }

        .el-input,
        .el-select {
          width: 220px;
        }
      }
    }
  }

  /*数据表格卡片*/
  .list-card {
    :deep(.el-card__body) {
      padding: 15px 20px 5px;
    }

    /*表格样式*/
    :deep(.el-table) {
      .date-value {
        color: #606266;
      }
    }
  }

  // 分页器
  .pagination {
    margin-top: 15px;
    display: flex;
    justify-content: flex-end;
  }
}

/* 报价单样式 */
.quotation-actions {
  margin-bottom: 20px;
  display: flex;
  gap: 10px;
  
  @media print {
    display: none;
  }
}

.quotation-container {
  background-color: #ffffff;
  padding: 25px;
  border: 1px solid #e1e8ed;
  position: relative;
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.05);
  border-radius: 8px;
  
  /* LOGO样式 - 置于右上角 */
  .top-logo {
    position: absolute;
    top: 10px;
    right: 10px;
    z-index: 1000;
    
    .logo-image {
      max-width: 120px;
      height: auto;
      display: block;
    }
  }
  
  .budget-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 24px;
    padding-bottom: 16px;
    border-bottom: 1px solid #ebeef5;
    position: relative;
    text-align: center;
    
    .budget-logo {
      position: absolute;
      top: 10px;
      right: 10px;
      
      .logo-image {
        max-width: 150px;
        height: auto;
      }
    }
    
    .budget-info {
      text-align: center;
      margin: 0 auto;
      width: 100%;
      
      h2 {
        margin: 0;
        font-size: 24px;
        color: #303133;
      }
    }
  }
  
  .budget-table {
    width: 100%;
    border-collapse: collapse;
    margin: 16px 0;
    box-shadow: 0 2px 8px rgba(0, 0, 0, 0.08);
    border-radius: 6px;
    overflow: hidden;
    
    td {
      padding: 10px 8px;
      border: 1px solid #d5d9dd;
      text-align: center !important;
      vertical-align: middle;
      font-size: 12px;
      line-height: 1.4;
      background-color: #ffffff;
    }
    
    tr:nth-child(even) td {
      background-color: #f8f9fa;
    }
    
    .yellow-bg {
      background-color: #f1c40f !important;
    }
    
    .yellow-bg td {
      background-color: #f1c40f !important;
      text-align: center;
      vertical-align: middle;
      font-weight: bold;
      color: #2c3e50 !important;
      font-size: 13px !important;
      padding: 12px 8px !important;
      border: 1px solid #f39c12 !important;
    }
    
    .category-row {
      background-color: #3498db !important;
    }
    
    .category-row td {
      background-color: #3498db !important;
      color: #ffffff !important;
      font-weight: bold !important;
      font-size: 12px !important;
      padding: 10px 15px !important;
      border: 1px solid #2980b9 !important;
    }
    
    .category-name {
      font-weight: bold;
      text-align: center !important;
      padding-left: 20px;
      color: #ffffff !important;
    }
    
    .table-header {
      background-color: #e8f4f8 !important;
    }
    
    .table-header td {
      background-color: #e8f4f8 !important;
      font-weight: bold;
      color: #2c3e50 !important;
      font-size: 12px !important;
      padding: 10px 6px !important;
      border: 1px solid #2c3e50 !important;
      text-align: center !important;
      vertical-align: middle !important;
    }
    
    .repeating-header {
      page-break-inside: avoid;
    }
    
    /* 规格简单布局样式 */
    .spec-simple-layout {
      padding: 8px;
      font-size: 11px;
      line-height: 1.4;
      text-align: center !important;
    }
    
    /* 规格内容HTML渲染样式 */
    .budget-table td[v-html] {
      line-height: 1.4;
      text-align: left;
      padding: 8px;
    }
    
    .spec-item {
      margin-bottom: 3px;
      padding-bottom: 3px;
      border-bottom: 1px solid #e8e8e8;
      
      &:last-child {
        border-bottom: none;
      }
    }
    
    .spec-line {
      width: 100%;
      text-align: center !important;
    }
    
    .spec-empty {
      text-align: center;
      color: #ccc;
      margin-bottom: 3px;
    }
    
    /* 操作按钮列样式 */
    .operation-cell {
      text-align: center;
      white-space: nowrap;
      
      .el-button {
        margin: 0 2px;
        padding: 4px 8px;
        font-size: 12px;
      }
    }
  }
  
  /* 清理了旧的样式规则 */
}

@media print {
  .quotation-actions,
  .no-print {
    display: none !important;
  }
  
  .el-dialog {
    width: 100% !important;
    margin: 0 !important;
    padding: 0 !important;
  }
  
  .el-dialog__header,
  .el-dialog__footer {
    display: none !important;
  }
  
  .el-dialog__body {
    padding: 0 !important;
  }
  
  .quotation-container {
    border: none;
    padding: 0;
  }
  
  /* 清理了打印样式 */
}

/* 全局移除所有输入框边框样式 */
:deep(.el-input) {
  .el-input__wrapper {
    box-shadow: none !important;
    border: none !important;
    background-color: transparent !important;
    padding: 0 !important;
  }
  
  .el-input__inner {
    border: none !important;
    outline: none !important;
    box-shadow: none !important;
    background-color: transparent !important;
    padding: 4px !important;
    text-align: center !important;
  }
}

/* 规格布局内的输入框特殊样式 */
.spec-simple-layout :deep(.el-input) {
  .el-input__inner {
    text-align: center !important;
  }
}

/* 确保所有输入框都居中 */
.quotation-container :deep(.el-input) {
  .el-input__inner {
    text-align: center !important;
  }
}

.quotation-container :deep(.el-textarea) {
  .el-textarea__inner {
    text-align: center !important;
  }
}

:deep(.el-input-number) {
  .el-input-number__wrapper {
    box-shadow: none !important;
    border: none !important;
    background-color: transparent !important;
  }
  
  .el-input__wrapper {
    box-shadow: none !important;
    border: none !important;
    background-color: transparent !important;
    padding: 0 !important;
  }
  
  .el-input__inner {
    border: none !important;
    outline: none !important;
    box-shadow: none !important;
    background-color: transparent !important;
    padding: 4px !important;
    text-align: center !important;
  }
}

:deep(.el-textarea) {
  .el-textarea__inner {
    border: none !important;
    outline: none !important;
    box-shadow: none !important;
    background-color: transparent !important;
    resize: none !important;
    padding: 4px !important;
    text-align: center !important;
    vertical-align: middle !important;
  }
}

/* 备注区域专用样式 */
:deep(.remarks-textarea) {
  .el-textarea__inner {
    background-color: #f8f9fa !important;
    border: 1px solid #dee2e6 !important;
    border-radius: 6px !important;
    padding: 12px !important;
    font-size: 13px !important;
    line-height: 1.6 !important;
    color: #495057 !important;
    text-align: left !important;
    box-shadow: 0 1px 3px rgba(0, 0, 0, 0.1) !important;
    transition: all 0.3s ease !important;
    
    &:focus {
      border-color: #80bdff !important;
      box-shadow: 0 0 0 0.2rem rgba(0, 123, 255, 0.25) !important;
      background-color: #ffffff !important;
    }
    
    &::placeholder {
      color: #6c757d !important;
      font-style: italic !important;
    }
  }
}
</style> 